package com.lp.mgt.controllers;


import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.mgt.commons.CustomResult;
import com.lp.mgt.entities.TableInfo;
import com.lp.mgt.entities.User;
import com.lp.mgt.services.DepartmentService;
import com.lp.mgt.services.FileAndExcelService;
import com.lp.mgt.services.FileService;
import com.lp.mgt.services.UserService;
import com.lp.mgt.utils.ExcelUtil;
import com.lp.mgt.utils.FileUtil;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserCtr {
	@Autowired
	private UserService userService;
	@Autowired
	private FileService fileService;
	@Autowired
	private DepartmentService deptService;
	@Autowired
	private FileAndExcelService fileAndExcelService;
	
	@GetMapping("/list")
	@RequiresPermissions("user:list")
	public CustomResult<User> getAllUsers(User user,HttpServletRequest request){
		log.info("查询用户列表：getAllUsers");
		User currentUser=(User) SecurityUtils.getSubject().getPrincipal();
		user.setUid(currentUser.getUid());//查是否关注
		String deptId=request.getParameter("deptId");
		if(!"".equals(deptId)&&!"0".equals(deptId)) {
			String[] ids=deptService.getChildsIdsWithParentId(deptId);
			user.setDeptIds(Arrays.asList(ids));
		}
		Map<String,Object> map=new HashMap<>();
		map=userService.getUsersWithTerms(user);
		return new CustomResult().success(true, map);
	}
	
	
	@GetMapping("/listPage")
	public ModelAndView toUserPage(ModelAndView mv) {
		mv.setViewName("user/userList.html");
		return mv;
	}

	
	@PostMapping("/register")
	public CustomResult<User> saveUserWhenRegister(User user) {
		log.info("用户注册：saveUserWhenRegister");
		MultipartFile[] files=new MultipartFile[10];
		files[0]=user.getHeadPicture();
		if(files[0]!=null) {
			String fileIds[]=fileService.avatarUpload(files,user.getUsername());
			String avatarId=fileIds[0]!=null?fileIds[0]:null;//关联头像id
			user.setAid(avatarId);
		}
		if(userService.saveUserWhenRegister(user)>0) {
			return new CustomResult<User>().success(true,"注册成功!");
		}else {
			return new CustomResult<User>().failure(false, "er001", "注册失败");
		}
	}

	@PostMapping("/update")
	public CustomResult<User> updateUserWhenEdit(User user) {
		log.info("用户更新：updateUserWhenEdit");
		if(userService.updateUserWhenEdit(user)) {
			return new CustomResult<User>().success(true,"注册成功!");
		}else {
			return new CustomResult<User>().failure(false, "er001", "注册失败");
		}
	}	
	
	@GetMapping("/checkUser")
	public CustomResult<User> checkUserWhenResetPass(@RequestParam("username") String username,@RequestParam("email") String email) {
		Boolean flag=userService.checkUserWithNameAndEmail(username,email);
		return new CustomResult<User>().success(flag);
	}
	
	
	
	@PostMapping("/sendEmail")
	public CustomResult<User> sendEmail(String username,String email) {
		CustomResult<User> result=new CustomResult<>();
		HashMap<String,String> map=userService.sendEmail(username,email);
		if (!"1000".equals(map.get("code"))){
			result.failure(false,map.get("code") , map.get("msg"));
		}else {
			result.success(true, map.get("code") , map.get("msg"));
		}
		return result;
	}
	//由于插件校验的特殊性没有返回公共的bean	
	@GetMapping("/nameValidate")
	public String nameValidate(@RequestParam(value="username") String username,@RequestParam("type") String type) {
		//用户名多个逗号
		if(username.indexOf(",")!=-1) {
			username=username.split(",")[1];
		}
		Boolean flag=userService.getUserByNameWhenRegisterOrLogin(username);
		Map<String, Boolean> map = new HashMap<>();
		if("r".equals(type)) {
			flag=!flag;
		}
		map.put("valid", flag);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
	}
	
	@GetMapping("/resetPassword")
	public CustomResult<User> resetPassword(User user) {
		Boolean flag=userService.updateUserWithPassword(user.getUsername(),user.getPassword());
		return new CustomResult<User>().success(flag,"成功");
	}
	
	@GetMapping("/listUserNames")
	//@RequiresPermissions("user:list")
	public CustomResult<User> getUserNames(User user){
		Map<String,Object> map=new HashMap<>();
		map=userService.getUsersWithTerms(user);
		return new CustomResult().success(true, map);
	}	
	
	
	@GetMapping("/getOtherInfo")
	//@RequiresPermissions("user:list")
	public CustomResult<User> getOtherUserInfoById(String uid){
		Map<String,Object> map=new HashMap<>();
		map=userService.getOtherUserInfoById(uid);
		return new CustomResult().success(true, map);
	}	
	
	
	@PostMapping("/removeUsers")
	public CustomResult<User> removeUserSingleOrBatch(String ids){
		Boolean flag=userService.removeUserSingleOrBatch(ids);
		return new CustomResult().success(flag);
	}
	
	//查询未被分配某角色的用户列表
	@RequestMapping("/getUserWithoutRole")
	public CustomResult<User> getUserWithoutRole(String roleId,String username,String page,String limit){
		Map<String,Object> map=userService.getUserWithoutRole(roleId,username,page,limit);
		return new CustomResult().success(true, map);
	}
	//查询已被分配某角色的用户列表
	@RequestMapping("/getUserWithRole")
	public CustomResult<User> getUserWithRole(String roleId){
		Map<String,Object> map=new HashMap<>();
		map.put("data",userService.getUserWithRole(roleId));
		return new CustomResult().success(true, map);
	}
	//分配用户
	@RequestMapping("/divideUser")
	public CustomResult<User> divideUserWithRoleId(String type,String roleId,String datas){
		List<User> list=(List<User>) JSON.parse(datas);
		Boolean flag=userService.divideUserWithRoleId(type,roleId,list);
		return new CustomResult().success(flag, null);
	}
	//生效失效
	@PostMapping("/effectiveOrinvalid")
	public CustomResult<User> effectiveOrinvalid(String ids,String type){
		Boolean flag=userService.effectiveOrinvalid(ids,type);
		return new CustomResult().success(flag);
	}
	
	//关注、取消关注
	@PostMapping("/focusUser")
	public CustomResult<User> focusUser(String id,String type){
		Boolean flag=userService.focusUser(id,type);
		return new CustomResult().success(flag);
	}
	
	
	//导出所有数据
	@GetMapping("/exportExcel")
	public void exportExcel(HttpServletResponse response) {
		User user=new User();
		User currentUser=(User) SecurityUtils.getSubject().getPrincipal();
		user.setUid(currentUser.getUid());//查是否关注
		List<User> datas=(List<User>) userService.getUsersWithTerms(user).get("rows");
		List<TableInfo> ti=fileAndExcelService.getTableInfoByName("mgt_user");
		ExcelUtil.exportExcel(response,ti, datas,"综合管理系统用户信息");
	}
	
	@PostMapping("/importExcel")
	public CustomResult<User> importExcel(@RequestParam("excelName") MultipartFile file){
		if(!file.isEmpty()) {
			String fileName=file.getOriginalFilename();
			//取文件类型
			String fileType=fileName.split("\\.")[1];
			if(fileType==null||(!"xlsx".equals(fileType)&&!"xls".equals(fileType))) {
				return new CustomResult<User>().failure(false, "0000", "文件格式有误!");
			}
			//String pathName=FileUtil.uploadFile(file, "D:\\\\入门到放弃/myWorkspace/import_export_files/");
			List<TableInfo> ti=fileAndExcelService.getTableInfoByName("mgt_user");
			ExcelUtil.importExcel(ti,file,new User());
		}
		
		return new CustomResult().success(true);
	}
	
}
